package com.hong.utils.exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: Administrator
 * @Date: 2018/7/22 20:58
 * @Description:
 */
public class ExchangerExample1 {

    /**
     * exchange(V v) v:代表传递的对象值。
     * <pre>
     *     NOTE:
     *          1.if the pair thread not reached change point,the thread will blocked.
     *          2.use the {@like Exchanger}must be paired.
     * </pre>
     * @param args
     */
    public static void main(String[] args) {
        final Exchanger<String> exchanger = new Exchanger<String>();

        new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName()+"start.");
                try {
                    String result = exchanger.exchange("I am come from T-A");
                    System.out.println(Thread.currentThread().getName()+"Get value ["+result+"]");
                    /*exchanger.exchange("I am come from T-A");*/
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"end.");
            }
        },"==A==").start();

        new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName()+"start.");
                try {
                    String result = exchanger.exchange("I am come from T-A1");
                    System.out.println(Thread.currentThread().getName()+"Get value ["+result+"]");
                    /*exchanger.exchange("I am come from T-A");*/
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"end.");
            }
        },"==A1==").start();

        new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName()+"start.");
                try {
                    TimeUnit.SECONDS.sleep(20);
                    String result = exchanger.exchange("I am come from T-B");
                    System.out.println(Thread.currentThread().getName()+"Get value ["+result+"]");
                    /*exchanger.exchange("I am come from T-A");*/
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"end.");
            }
        },"==B=").start();
    }
}
